import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { addCartAPI, fetchGoodDetailAPI } from "@/api/detailApi";
import type { Detail } from "@/types/detail";


const useDetailStore = defineStore("detailStore", () => {
    /*商品详情*/
    const detail = ref<Detail>(<Detail>{});
    const mainPictures = computed(() => detail.value.mainPictures);
    const similarProducts = computed(() => detail.value.similarProducts);
    const properties = computed(() => detail.value.details.properties);
    const pictures = computed(() => detail.value.details.pictures);
    const localdata = ref({});

    /*获取商品详情的请求函数*/
    const fetchGoodDetail = async (id: string): Promise<void> => {
        const { result }: { result: Detail } = await fetchGoodDetailAPI(id);
        detail.value = result;
        localdata.value = {
            _id: result.id,
            name: result.name,
            goods_thumb: result.mainPictures[0],
            spec_list: result.specs.map(item => ({
                name: item.name,
                list: item.values,
            })),
            sku_list: result.skus.map(item => ({
                _id: item.id,
                goods_id: detail.value.id,
                goods_name: detail.value.name,
                image: item.picture,
                price: item.price,
                stock: item.inventory,
                sku_name_arr: item.specs.map((item) => item.valueName),
            })),
        };
    };

    /*加入购物车的请求函数*/
    const addCart = async (data: { skuId: string, count: number }): Promise<void> => {
        await addCartAPI(data);
    };

    return {
        detail,
        mainPictures,
        similarProducts,
        properties,
        pictures,
        localdata,
        fetchGoodDetail,
        addCart,
    };
});

export default useDetailStore;
